package com.bbh.plugin.single.privilege.core.service;


import com.bbh.plugin.single.privilege.core.entity.RoleResource;
import com.bbh.common.domain.Condition;
import com.bbh.common.utils.ConvertUtils;
import com.bbh.common.utils.Exceptions;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.bbh.common.base.service.BaseService;
/**
 * Created by roman_000 on 2015/7/15.
 */
@Service
@Transactional
public class RoleResourceService extends BaseService<RoleResource, String> {

    //保存权限
    public void insert(String roleId, List<HashMap<String, Object>> checkParams) {
        if (CollectionUtils.isNotEmpty(checkParams)) {
            RoleResource roleResource;
            for (Map<String, Object> map : checkParams) {
                String id = ConvertUtils.convert2String(map.get("id"));
                Boolean checked = ConvertUtils.convert2Boolean(map.get("checked"));
                if (checked) {
                    roleResource = new RoleResource();
                    roleResource.setId(getId());
                    roleResource.setRoleId(roleId);
                    roleResource.setResourceId(id);
                    try {
                        super.insert(roleResource);
                    } catch (DuplicateKeyException ex) {//键冲突的异常,可以继续
                        logger.info(Exceptions.getStackTraceAsString(ex));
                    }
                } else {
                    super.deleteByPrimaryKey(id);
                }
            }
        }
    }

    //删除所有权限
    //roleId 对应 角色的id
    public void del(String roleId) {
        Condition condition = new Condition();
        condition.put("EQ_roleId", roleId);
        List<RoleResource> roleResourceList = this.selectList(condition, null);
        if (CollectionUtils.isNotEmpty(roleResourceList)) {
            String idStr = "";
            for (RoleResource ro : roleResourceList) {
                idStr += ro.getId() + ",";
            }
            idStr = idStr.substring(0, idStr.length() - 1);
            String[] ids = idStr.split(",");
            super.delete(ids);
        }
    }

    public static String getId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
